from django.http import HttpResponse
from django.shortcuts import render

# Create your views here.
from DjangoModel.models import Person, IDCard, Cat, Dog


def hello(request):
    return HttpResponse("hello world")

def addperson(request):

    username = request.GET.get("username")

    person = Person()

    person.p_name = username
    person.save()

    return HttpResponse("用户创建成功 %s" % person.p_name)


def addidcard(request):

    id_num = request.GET.get("idnum")

    idcard = IDCard()

    idcard.id_num = id_num

    idcard.save()

    return HttpResponse("idcard创建成功 %s" % idcard.id_num)


def bindcard(request):

    person = Person.objects.last()

    idcard = IDCard.objects.last()

    idcard.id_person = person

    idcard.save()

    return HttpResponse("绑定成功")


def addcat(request):

    cat = Cat()

    cat.a_name = 'Tom'

    cat.c_eat = 'Fish'

    cat.save()

    return HttpResponse("cat创建成功 %d " % cat.id)


def adddog(request):

    dog = Dog()

    dog.a_name = 'Ann'

    dog.save()

    return HttpResponse("dog创建成功 %d " % dog.id)


def upload_file(request):

    if request.method == "GET":
        return render(request,'upload.html')
    elif request.method == "POST":
        icon = request.FILES.get("icon")
        # 将上传的icon写入文件/home/extraxue/pythonProject/p1/HelloDjango/static/test.txt中（以二进制追加写的方式）
        with open("/home/extraxue/pythonProject/p1/HelloDjango/static/test.txt",'wb') as save_file:
            # 由于文件是以数据包的形式上传的，则需要循环迭代上传
            for part in icon.chunks():
                save_file.write(part)
                # 每次写了之后都要记得flush()
                save_file.flush()
        return  HttpResponse("文件上传成功")
